import { useState, useRef, useImperativeHandle } from 'react';
import { Button } from 'antd'
import BaseLayout from '../../../layouts/BaseLayout/BaseLayout.jsx'

const ChildA = (props) => {
	const [count2, setCount2] = useState(66);

	const fn = () => {
		console.log('ChildA', 'fn');
		props.fn1(count2);
	};
	//供父级调用
	useImperativeHandle(props.childARef, () => ({
        fn2: (params)=>{
			setCount2(count2 + 1);
			console.log('ChildA', 'fn2', params, count2);
        }
    }))

	return (<div className="note-demo-child-box">
		<Button onClick={() => fn()}>在[子组件]调用[父组件]的fn1:{count2}</Button>
	</div>);
};

const Demo = () => {
	const [count1, setCount1] = useState(11);
	const childARef = useRef();
	//供子级调用
	const fn1 = (params) => {
		setCount1(count1 + 1);
		console.log('parent', 'fn1', count1, params);
	}
	const fn = () => {
		console.log('parent', 'fn');
		childARef.current.fn2(count1);
	};

	return (
		<BaseLayout>
			<div className='note-title-a'>hooks 子父通信</div>
			<div className='note-example-box'>
				<div className="note-example-intro">子父之间数据如何互传,子父之间的函数如何互调。</div>
				<div className="note-demo-parent-box">
					<Button onClick={() => fn()}>在[父组件]调用[子组件]的fn2:{count1}</Button>
					<ChildA childARef={childARef} fn1={fn1}></ChildA>
				</div>
				<div className="note-code-case">
					<textarea defaultValue={codeVal1} style={{height: '620px'}}></textarea>
					<textarea defaultValue={codeVal2} style={{height: '440px'}}></textarea>
				</div>
			</div>
		</BaseLayout>
	);
};

const codeVal1 = `父组件 Demo.jsx
const Demo = () => {
	const [count1, setCount1] = useState(11);
	const childARef = useRef();
	//供子级调用
	const fn1 = (params) => {
		setCount1(count1 + 1);
		console.log('parent', 'fn1', count1, params);
	}
	const fn = () => {
		console.log('parent', 'fn');
		childARef.current.fn2(count1);
	};

	return (
		<BaseLayout>
			<div className='note-title-a'>hooks 子父通信</div>
			<div className='note-example-box'>
				<div className="note-demo-parent-box">
					<button onClick={() => fn()}>在[父组件]调用[子组件]的fn2:{count1}</button>
					<ChildA childARef={childARef} fn1={fn1}></ChildA>
				</div>
			</div>
			<div className="note-code-case">
				<textarea defaultValue={codeVal} style={{height: '800px'}}></textarea>
			</div>
		</BaseLayout>
	);
};
`;
const codeVal2 = `子组件 ChildA.jsx
const ChildA = (props) => {
	const [count2, setCount2] = useState(66);

	const fn = () => {
		console.log('ChildA', 'fn');
		props.fn1(count2);
	};
	//供父级调用
	useImperativeHandle(props.childARef, () => ({
        fn2: (params)=>{
			setCount2(count2 + 1);
			console.log('ChildA', 'fn2', params, count2);
        }
    }))

	return (<div className="note-demo-child-box">
		<button onClick={() => fn()}>在[子组件]调用[父组件]的fn1:{count2}</button>
	</div>);
};`;
export default Demo;
